package com.yss.reportworld.controller;

import com.yss.common.core.constant.Constants;
import com.yss.common.core.exception.BusinessException;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.core.web.controller.BaseController;
import com.yss.common.core.web.domain.AjaxResult;
import com.yss.common.core.web.page.TableDataInfo;
import com.yss.common.logger.annotation.Log;
import com.yss.common.logger.enums.BusinessType;
import com.yss.common.redis.service.RedisService;
import com.yss.common.security.annotation.RequiresPermissions;
import com.yss.common.security.utils.DictUtils;
import com.yss.reportworld.domain.rule.RCheckObject;
import com.yss.reportworld.enums.ReportWorldEnum;
import com.yss.reportworld.service.*;
import com.yss.system.api.domain.SysDictData;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 规则管理Controller
 *
 * @author yss
 * @date 2023-03-29
 */
@RestController
@RequestMapping("/rule")
public class RuleController extends BaseController {
    @Autowired
    private IRuleService ruleService;
    @Autowired
    private IRCheckTypeService rCheckTypeService;
    @Autowired
    private IRCheckObjectService rCheckObjectService;
    @Autowired
    private ISqlScriptService sqlScriptService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private RedisService redisService;

    /**
     * 初始化加载报表世界规则
     *
     * @return
     */
    @RequiresPermissions("reportworld:rule:list")
    @Log(title = "规则管理", businessType = BusinessType.OTHER)
    @PutMapping("/init")
    public AjaxResult init() {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("regulationRuleList", rCheckTypeService.selectRCheckTypeTreeList());
        // 获取备份的表,和最新的版本号
        List<SysDictData> sysDictDataList = sqlScriptService.getReductionVersion(false);
        ajax.put("hisVersions", sysDictDataList);
        ajax.put("customerTree", customerService.selectCustomerTreeList());
        return ajax;
    }

    /**
     *
     */
    @RequiresPermissions("reportworld:rule:list")
    @GetMapping("/list")
    public TableDataInfo list(RCheckObject rCheckObject) {
        startPage();
        List<RCheckObject> list = rCheckObjectService.selectRCheckObjectList(rCheckObject);
        // 获取所有规则类型的名称集合
        Map<String, String> map = rCheckTypeService.getRuleTypeName();
        if (StringUtils.isNotEmpty(map)) {
            for (RCheckObject checkObject : list) {
                checkObject.setRuleTypeId(map.get(checkObject.getRuleTypeId()));
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出Execle文件，提供给升级工具
     *
     * @return
     * @throws Exception
     */
    @RequiresPermissions("reportworld:rule:export")
    @Log(title = "规则管理", businessType = BusinessType.EXPORT)
    @PostMapping(value = "/downRuleExecl")
    public void downRuleExecl(HttpServletResponse response, RCheckObject rCheckObject) throws Exception {
        if (StringUtils.isNull(rCheckObject)) {
            throw new BusinessException("没有获取到要导出的规则管理信息！");
        }
        if (null == rCheckObject.getExportType()) {
            throw new BusinessException("请选择要导出方式！");
        }
        if (1 == rCheckObject.getExportType()) {
            if (StringUtils.isEmpty(rCheckObject.getRuleTypeId())) {//导出方式是规则分类
                throw new BusinessException("请选择要导出的规则分类！");
            }
        } else {
            if (StringUtils.isEmpty(rCheckObject.getIds())) {
                throw new BusinessException("请选择要导出规则的具体校验对象信息！");
            }
        }
        if (StringUtils.isEmpty(rCheckObject.getDataBaseType())) {
            throw new BusinessException("请选择要导出的规则的数据库类型！");
        }
        ruleService.downRuleExecl(response, rCheckObject);
    }


    /**
     * 读取报表部署报表
     */
    @RequiresPermissions("reportworld:rule:readExecl")
    @Log(title = "规则管理", businessType = BusinessType.IMPORT)
    @PostMapping("/readExecl")
    public AjaxResult readExecl(MultipartFile file, String hisVersion, HttpServletResponse response) throws Exception {
        String sql = ruleService.getRuleSql(file, hisVersion);
        redisService.setCacheObject("RULESQL", sql);
        return success(sql);
    }

    /**
     * 导出SQL文件
     */
    @RequiresPermissions("reportworld:rule:readExecl")
    @Log(title = "规则管理", businessType = BusinessType.EXPORT)
    @PostMapping("/handleDownSql")
    public void handleDownSql(HttpServletResponse response) throws IOException {
        if (redisService.hasKey("RULESQL")) {
            String sql = redisService.getCacheObject("RULESQL");
            redisService.deleteObject("RULESQL");
            IOUtils.write(sql, response.getOutputStream(), Constants.UTF8);
        }
    }

}
